import React, {useCallback, useEffect, useState} from "react"
import {Pageable} from "../../utils/Page";
import {
    QueryEmployeeOperateRecordResponse,
    queryEmployeeOperateRecords,

} from "../../apis/EmployeeOperateRecordApi";
import {ConfigProvider, Table, theme} from "antd";
import {
    castFilterValue,
    mergePaginationAndPageable,
    useTableFilterDateRangeColumnProps
} from "../../utils/AntdTableUtils";
import DataPageLayout from "../../components/DataPageLayout";
import {NumberIdAndName} from "../../types/BasicModels";
import {getEmployeeSummaries} from "../../apis/EmployeeApi";
import {observerDashboardPageWrapper} from "../../components/dashboardPages/ObserverDashboardPageWrapper";
import {LocalDate, OffsetDateTime} from "@js-joda/core";
import {ContentItem} from "../../apis/EmployeeOperateRecordApi";
import {Link} from "react-router-dom";
import {DATE_WITH_TIME_FORMATER} from "../../utils/Date";

export interface pageProps {

}
const EmployeeOperateRecordPage: React.FC<pageProps> = () => {
    const [pageable, setPageable] = useState(new Pageable())
    const [data, setData] = useState<QueryEmployeeOperateRecordResponse[]>([])
    const [loading, setLoading] = useState(false)
    const [totalElements, setTotalElements] = useState(0)


    const [startCreatedDate, setStartCreatedDate] = useState<string>()
    const [endCreatedDate, setEndCreatedDate] = useState<string>()
    const [operatorIds, setOperatorIds] = useState<number[]>([])

    let query = useCallback(() => {
        setLoading(true)
        queryEmployeeOperateRecords({operatorIds: operatorIds, createdStartDate: startCreatedDate, createdEndDate: endCreatedDate,}, pageable).then(response => {
            setTotalElements(response.data.totalElements)
            setData(response.data.content)
        }).finally(() => {
            setLoading(false)
        })
    }, [...pageable.toDependencyList(), operatorIds, startCreatedDate, endCreatedDate]);
    useEffect(() => {
        query()
    }, [query]);

    const [employees, setEmployees] = useState<NumberIdAndName[]>([])
    useEffect(() => {
        getEmployeeSummaries().then(response => {
            setEmployees(response.data)
        })
    }, []);

    let dataRangeFilterProps = useTableFilterDateRangeColumnProps<QueryEmployeeOperateRecordResponse>("createdDateTime", {
        handleSearch(value) {
            setStartCreatedDate(value ? LocalDate.parse(value[0].format()).toString() : undefined)
            setEndCreatedDate(value ? LocalDate.parse(value[1].format()).toString() : undefined)
        }
    });

    let token = theme.useToken();

    return <>
        <DataPageLayout>
            <ConfigProvider componentSize={"small"}>
                <Table loading={loading} dataSource={data} rowKey={"id"} pagination={{
                    current: pageable.page,
                    pageSize: pageable.size,
                    total: totalElements,
                }} onChange={(pagination, filters, sorter) => {
                    setOperatorIds(filters.createdBy as number[])
                    setPageable(mergePaginationAndPageable(pagination, pageable, sorter))
                }}>
                    <Table.Column<QueryEmployeeOperateRecordResponse> key={"content"} dataIndex={"content"}
                                                                      title={"记录"}
                                                                      render={(value: ContentItem[], item) => {
                                                                          return <>
                                                                              {value.map((item, index) => {
                                                                                  if (item.resource) {
                                                                                      let href: string
                                                                                      let id = item.resource.id;
                                                                                      switch (item.resource.type) {
                                                                                          case "MarketDeliveryOrder":
                                                                                              href = `/markets/deliveryOrders/${id}`;
                                                                                              break;
                                                                                          case "MarketOrder":
                                                                                              href = `/markets/orders/${id}`
                                                                                              break;
                                                                                      }
                                                                                      return <Link key={index}
                                                                                                   to={href}>{item.text}</Link>
                                                                                  } else if (item.highlight) {
                                                                                      return <span key={index}
                                                                                                   style={{color: token.token.gold7}}>{item.text}</span>
                                                                                  } else {
                                                                                      return item.text
                                                                                  }
                                                                              })}
                                                                          </>
                                                                      }}/>
                    <Table.Column key={"createdBy"} dataIndex={["createdBy", "name"]} title={"操作人"}
                                  filters={employees.map(it => ({text: it.name, value: it.id}))}
                                  filterSearch/>
                    <Table.Column<QueryEmployeeOperateRecordResponse> key={"createdDateTime"}
                                  {...dataRangeFilterProps}
                                  dataIndex={["createdDateTime"]} title={"时间"}
                                  render={(value) => {
                                      return value.format(DATE_WITH_TIME_FORMATER);
                                  }}/>
                </Table>
            </ConfigProvider>
        </DataPageLayout>
    </>
}


export default observerDashboardPageWrapper(EmployeeOperateRecordPage, "employees/operateRecords", "操作记录")
